﻿#include "filethread.h"

FileThread::FileThread(QString filepath,QString filename,FileTrans_Socket*& sock,uint filesize)
{
    m_sock = sock;
    m_filename = filename;
    m_filepath = filepath;
    m_filesize = filesize;
    m_sendsize = 0;
    connect(&m_timer1,&QTimer::timeout,this,[=](){
        m_timer1.stop();
        sendFileData();
    });
}

void FileThread::sendFileData()
{
    qint64 r = 0;
    char buff[1024];
    while(1)
    {
        r = m_file.read(buff,1024);//从文件中读取
        if(r > 0)
        {//读到了
            r = m_sock->write(buff,r);//发给接收端
            if(r > 0)
            {
                m_sendsize += r;//累加已经发送的文件大小

                if(m_sendsize >= m_filesize) break;
            }
            else
            {

                break;
            }
        }
        else
        {

            break;
        }
    }
    m_file.close();
    m_file.remove();
}

void FileThread::run()
{
    m_file.setFileName(m_filepath);
    if(m_file.open(QIODevice::ReadOnly))
    {
        QString str=QString("%1&%2").arg(m_filename).arg(m_filesize);
        m_sock->write(str.toUtf8(),str.toUtf8().length()+1);
        m_timer1.start(20);
    }
    //exec();
}
